<template>
  <el-row justify="center" align="middle" class="wrap">
    <el-col :xs="22" :sm="14" :md="10" :lg="8" :xl="6">
      <el-card shadow="never" class="box">
        <template #header>
          <div class="card-header">新用户注册</div>
        </template>

        <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="80px" @keyup.enter="handleSubmit">
          <el-form-item label="账号" prop="username">
            <el-input v-model.trim="form.username" placeholder="3~16 位字母/数字/下划线" maxlength="16" clearable />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" show-password placeholder="6~20 位大小写字母+数字+符号"
              maxlength="20" />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPwd">
            <el-input v-model="form.confirmPwd" type="password" show-password placeholder="请再次输入密码" maxlength="20" />
          </el-form-item>


          <el-form-item label="" prop="verifyCode" for="verifyCode">
            <div style="width: 400px;height: 45px;margin: auto;">
              <el-input id="verifyCode" v-model="form.verifyCode" placeholder="请输入验证码" class="verifyCode"
                style="width: 250px;"></el-input>
              <el-image style="float: right;width: 120px;height: 45px;border-radius: 10px;" :src="imgObj.captchUrl"
                @click="getCaptch">
              </el-image>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="default" :loading="loading" @click="handleSubmit">立即注册</el-button>
            <el-button size="default" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="tip">
          已有账号？
          <el-link type="primary" :underline="false" @click="$router.push('/')">去登录</el-link>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from "@/utils/request"
import loginApi from '../api/LoginApi'

/* --------------------- 表单数据 --------------------- */
const ruleFormRef = ref()
const loading = ref(false)
//定义验证码对象，用于接收与验证码相关数据
const imgObj = reactive({
  captchUrl: "", //验证码Base64字符串
})
const form = reactive({
  username: '',
  password: '',
  confirmPwd: '',
  verifyCode: '',
  codeId: '',
})

/* --------------------- 校验规则 --------------------- */
const equalToPassword = (rule, value, callback) => {
  if (value !== form.password) callback(new Error('两次输入密码不一致'))
  else callback()
}

const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { pattern: /^\w{3,16}$/, message: '账号格式有误', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{6,20}$/,
      message: '需包含大小写字母、数字及特殊字符',
      trigger: 'blur'
    }
  ],
  confirmPwd: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: equalToPassword, trigger: 'blur' }
  ],

}



/* --------------------- 确认注册按钮--------------------- */
async function handleSubmit() {
  //使用正则表达式校验账号密码，暂时注释掉了
  const valid = await ruleFormRef.value.validate().catch(() => false);
  if (!valid){
    ElMessage.error('格式错误')
    return;
  } 
  loading.value = true;
  try {

    const res = await request.post('/register/register', form)
    if (res.data.code == 200) {
      ElMessage.success('注册成功，即将跳转登录页')
      setTimeout(() => location.replace('/'), 1500)
    } else if (res.data.code == 528) {
      ElMessage.error('用户名或密码不能为空')
      resetForm();
    } else if (res.data.code == 529) {
      ElMessage.error('用户已存在')
      resetForm();
    } else {
      ElMessage.error('注册失败')
      resetForm();
    }
  } catch (e) {
    ElMessage.error('网络错误')
    resetForm();
  } finally {
    loading.value = false
  }
  // })
}

//获取验证码图片
const getCaptch = async () => {
  //发送请求获取验证码信息
  let res = await loginApi.getCaptcha(form);
  if (res.data.success) {
    imgObj.captchUrl = res.data.data.imageBase64;
    form.codeId = res.data.data.codeId;
  } else {
    ElMessage.error("加载验证码失败");
  }
}



function resetForm() {
  form.username = '';
  form.password = '';
  form.confirmPwd = '';
  form.verifyCode = '';
  getCaptch();
}

//vue对象挂载到元素时，自动触发onMounted函数，在函数中调用获取验证码方法
onMounted(() => {
  getCaptch();
})
</script>

<style scoped>
.wrap {
  min-height: 100vh;
  background-image: url("../assets/login_img.jpg");
}

.box {
  border-radius: 8px;
  background: #d9e6f3;
}

.card-header {
  text-align: center;
  font-size: 18px;
  font-weight: 600;
}

.captcha {
  height: 32px;
  cursor: pointer;
  vertical-align: middle;
}

.tip {
  text-align: center;
  margin-top: 12px;
  font-size: 14px;
  color: #666;
}

/* 输入框高度统一 */
.captcha-input :deep(.el-input__inner) {
  height: 40px;
}

/* 去掉 append 的 padding 和 border */
.captcha-input :deep(.el-input-group__append) {
  padding: 0;
  border: none;
  background: transparent;
}

/* 验证码图片：更宽 + 同高 */
.captcha-img {
  display: block;
  width: 140px;
  /* 🔥加宽*/
  height: 40px;
  object-fit: cover;
  cursor: pointer;
  border-radius: 0 4px 4px 0;
}
</style>